package com.example.lxrbf;

import java.util.*;
import java.io.*;

import com.example.lxrbf.db.*;
import com.xqkad.MyIO;
import com.xqkad.StorageList;

import android.content.*;
import android.database.*;
import android.net.*;
import android.provider.*;
import android.util.Log;

public class Lxrbf {
	public static String 	dirname = "1xqkad",
							filename = "lxrbf.db";
							 
	private String storagePath, dbpath, dbpathbf;
	private MySQLiteController ctrl;
	private MainActivity mui;
	private ArrayList<Card> list = new ArrayList<Card>(),
							list_bf = new ArrayList<Card>();
	
	public Lxrbf(MainActivity mainActivity) {
		mui = mainActivity;
		init();
		ctrl = new MySQLiteController(mainActivity);
		setTV();
	}
	
	private void init() {
		initIO();
	}
	
	private void initIO() {
		File dbdir, dbdirbf, dbfile, dbfilebf;
		try {
			storagePath = new StorageList(mui).getVolumePaths()[0];
			dbpath = "/data/data/com.example.lxrbf/databases/"+
					MySQLiteController.dbname;
			dbpathbf = storagePath+"/"+dirname+"/"+filename;
			dbdir = new File("/data/data/com.example.lxrbf/databases/");
			dbdirbf = new File(storagePath+"/"+dirname+"/");
			dbfile = new File(dbpath);
			dbfilebf = new File(dbpathbf);
			if(!dbdir.exists())
				dbdir.mkdirs();
			if(!dbdirbf.exists())
				dbdirbf.mkdirs();
			if(dbfile.exists())
				MyIO.deleteFile(dbfile, null);
			if(dbfilebf.exists())
				MyIO.copyFile(dbpathbf, dbpath, 2048, null);
		} catch (Exception e) {
			mui.sc("IO错误");
		}
	}
	
	public void setTV() {
		int re = setlist(mui);
		if(re == -1) {
			mui.sc("setlist -1");
			return;
		}
		mui.setUI(""+list.size(), ""+list_bf.size());
	}
	
	private int setlist(Context context) {
		int re = -1;
		try {
			list.clear();
			Uri uri = ContactsContract.Contacts.CONTENT_URI;
			String[] projection = new String[] {
					ContactsContract.Contacts._ID,
					ContactsContract.Contacts.DISPLAY_NAME
			};
			Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
			int i = 0;
			if (cursor != null && cursor.moveToFirst()) {
				do {
					Long id = cursor.getLong(0);
					String name = cursor.getString(1);
					String[] phoneProjection = new String[] {
	                        ContactsContract.CommonDataKinds.Phone.NUMBER
	                };
					String[] phoness = new String[8];
					Cursor phonesCusor = context.getContentResolver().query(
	                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
	                        phoneProjection,
	                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id,
	                        null,
	                        null);
	                if(phonesCusor.getCount() == 0)
	                	continue;
					if (phonesCusor != null && phonesCusor.moveToFirst()) {
	                	int pcIndex=0;//phones Cusor Index
	                	do {
	                		String rawsum = phonesCusor.getString(0);//.replaceAll("[^0-9]", "");
	                        String sum = "";
	                        
	                        if(rawsum != null && !"".equals(rawsum)){
	                        	for(int d=0;d<rawsum.length();d++){
	                        		if(rawsum.charAt(d)>=48 && rawsum.charAt(d)<=57){
	                        			sum+=rawsum.charAt(d);
	                        		}
	                        	}
	                        }
	                        if(pcIndex < 8)
	                        	phoness[pcIndex] = sum;
	                        pcIndex++;
	                    }while (phonesCusor.moveToNext());
	                }
	                list.add(new Card(name, phoness));
	                i++;
				}while (cursor.moveToNext());
			}
			re = 1;
		} catch (Exception e) {
			return -1;
		}
		
		try {
			list_bf.clear();
			if(ctrl.selectAll() != null) {
				for(String name : ctrl.selectAll()) {
					String[] phones = ctrl.selectPhones(name);
					list_bf.add(new Card(name, phones));
				}
			}
				
			re = 1;
		} catch (Exception e) {
			return -1;
		}
		return re;
	}
	
	public int bf() {
		int re = -1;
		try {
			if(list == null)
				return -1;
			for (Card card : list) {
				ctrl.delete(card.name);
				int a = ctrl.insert(card.name, card.phones);
				if(a == -1)
					mui.sca("备份 "+card.name+"失败");
			}
			MyIO.copyFile(dbpath, dbpathbf, 2048, null);
			re = 1;
		} catch (Exception e) {}
		if(re == 1)
			setTV();
		return re;
	}
	
	public int hf() {
		int re = -1;
		int fint = 0;
		boolean iseq = false;
		for(Card c : list_bf) {
			for(Card c2 : list) {
				if(c.isequal(c2)) {
					iseq = true;
					break;
				}
			}
			if(!iseq) {
				re = hfone(c.name, c.phones);
				if(re != 1) {
					return re;
				}else fint++;
			}else iseq = false;
		}
		if(fint != 0 && re != -1) {
			mui.sc("已恢复 "+fint+" 个");
			setTV();
		}
		return re;
	}
	
	public int hfone(String name, String[] phones) {
		int re = -1;
		if(name == null || phones == null)
			return -1;
		for (String phone : phones) {
			if(phone != null)
				re = 2;
		}
		if(re == 2) {
			re = -1;
		}else return -1;
		
		try {
			ContentResolver contentResolver=mui.getContentResolver();
			Cursor cursor=contentResolver.query(Uri.parse(
					"content://com.android.contacts/raw_contacts"),
					new String[]{"_id"},null,null,null);
			int count = 0;
			if(cursor.moveToLast()) {
				count=cursor.getInt(cursor.getColumnIndex("_id"));
	            count++;
			}else count=1;
			//cv id
			ContentValues cv=new ContentValues();
			cv.put("contact_id",count);
			contentResolver.insert(Uri.parse("content://com.android.contacts/raw_contacts"),cv);
			//name
			cv.clear();
			cv.put("raw_contact_id",count);
			cv.put("data1", name);
			cv.put("mimetype","vnd.android.cursor.item/name");
			contentResolver.insert(Uri.parse("content://com.android.contacts/data"),cv);
			//phones
			for(String phone : phones) {
				if(phone == null)
					continue;
				cv.clear();
				cv.put("raw_contact_id",count);
				cv.put("data1",phone);
				cv.put("mimetype","vnd.android.cursor.item/phone_v2");
				contentResolver.insert(Uri.parse("content://com.android.contacts/data"),cv);
			}
			re = 1;
		} catch (Exception e) {}
		return re;
	}
	
}
